package com.hkdrjxy.android.signed;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

/**
 * D:\\Android\\android-sdk\\ 请替换为Android-sdk所在目录
 * D:\\Android\\xuyahui_android_key.keystore 请替换为签名文件
 * 需要先运行一下Android的项目，在bin目录生成classes.dex resources.ap_之后才可以运行此程序
 * @author xuyahui 2012-11-28 <br>
 */
public class SignedMain {
	public static final String PROJECT_PATH = "D:\\Android\\workspace\\Dota\\"; // 工程的具体路径。后面很多地方会用到
	
	public static final String APK_OUT_PATH = "C:\\Users\\xuyahui\\Desktop\\Dota\\"; // APK输出路径
	
	public static final String CHANNEL[] = new String[]{"机锋网","安智网","安卓网","木蚂蚁","N多网","应用汇","3G","360网","百度"};

	public static void main(String[] args) {
//		try {
//			System.out.println("start--");
////			Process process = Runtime.getRuntime().exec("D:\\android-sdk-windows\\platform-tools\\dx.bat --dex --output="+PROJECT_PATH+"bin\\classes.dex "+PROJECT_PATH+"bin\\classes\\  "+PROJECT_PATH+"libs\\pinyin4j-2.5.0.jar" );
//			Process process = Runtime.getRuntime().exec(
//					"D:\\Android\\android-sdk\\platform-tools\\dx.bat --dex --output="
//							+ PROJECT_PATH + "bin\\classes.dex " + PROJECT_PATH
//							+ "bin\\classes\\");
//			process.waitFor();
//			process.destroy(); // 先完成class--》dex的打包。因为java文件未曾改变过，所以打包一次就够。
//			System.out.println("start--replace---");
//			replaceChannel(CHANNEL); // 替换渠道号
//			System.out.println("batch pack finished!");
//		} catch (IOException e) {
//			e.printStackTrace();
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
		System.out.println("start");
		replaceChannel(CHANNEL); // 替换渠道号
		System.out.println("batch pack finished!");
		
	}

	public static void replaceChannel(String channel[]) {
		try {
			String outPath = PROJECT_PATH + "AndroidManifest.xml"; // 输出文件位置
			String tempPath = PROJECT_PATH + "AndroidManifest.xml_bak"; // 临时文件位置
			BufferedReader reader;
			BufferedWriter writer;
			for (int channelid = 0; channelid < channel.length; channelid++) {
				String line = null;
//				reader = new BufferedReader(new FileReader(tempPath));
//				writer = new BufferedWriter(new FileWriter(outPath));
				reader = new BufferedReader(new InputStreamReader(new FileInputStream(tempPath),"UTF-8"));
				writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outPath), "UTF-8"));
				while ((line = reader.readLine()) != null) {
					if (line.contains("%channel%"))
						line = line.replace("%channel%", channel[channelid]);// 设置渠道号
					writer.write(line + "\r\n");
					writer.flush();
				}
				writer.close();
				reader.close();
				System.out.println(channel[channelid]+"replace AndroidManifest end");
				generatePackage(channel[channelid]); // 一次渠道号的更改完成。可以进行打包了
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void generatePackage(String apkName) {
		try {
			Process process = null;
			
			String resources = "aapt package -f -M "
					+ PROJECT_PATH
					+ "AndroidManifest.xml -S "
					+ PROJECT_PATH
					+ "res -A "
					+ PROJECT_PATH
					+ "assets -I D:\\Android\\android-sdk\\platforms\\android-8\\android.jar -F "
					+ PROJECT_PATH + "bin\\resources.ap_";
			
			String builderApk = "D:\\Android\\android-sdk\\tools\\apkbuilder.bat "
					+ PROJECT_PATH + "bin\\unsigned.apk -u -z "
					+ PROJECT_PATH + "bin\\resources.ap_ -f "
					+ PROJECT_PATH + "bin\\classes.dex -rf "
					+ PROJECT_PATH + "src -rj " + PROJECT_PATH
					+ "\\libs";
			
			String sigend = "jarsigner -keystore D:\\Android\\xuyahui_android_key.keystore -storepass hahadaxiao -keypass hahadaxiao -signedjar "+APK_OUT_PATH
					+ apkName
					+ ".apk "
					+ PROJECT_PATH
					+ "bin\\unsigned.apk xuyahui";
			
//            String[] cmds = {resources,builderApk,sigend};//command and arg
//            ProcessBuilder builder = new ProcessBuilder(cmds);
//            //both read inputstream and errstream
//            builder.redirectErrorStream(true);
//            process = builder.start();
            
			process = Runtime.getRuntime().exec(resources); // 将资源文件打包resources.ap_
			printLog1(process);
			process.waitFor();
			process.destroy();
			System.out.println(apkName+"resources.ap_ end");
			
			process = Runtime.getRuntime().exec(builderApk); // 生成未签名的apk
			printLog1(process);
			process.waitFor();
			process.destroy();
			System.out.println(apkName+"apkbuilder end");
			
			process = Runtime.getRuntime().exec(sigend); // 对apk进行签名
			printLog1(process);
			process.waitFor();
			process.destroy();
			System.out.println(apkName+"jarsigner end");
			
			System.out.println(apkName + " finished..."); // 一条渠道的打包完成。文件会输出到指定目录
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void printLog1(Process p){
		 BufferedReader br;
		try {
			br = new BufferedReader(new InputStreamReader(p
			            .getInputStream(),"UTF-8"));
		
	            String readLine = br.readLine();
	            while (readLine != null) {
	               System.out.println(readLine);
	               readLine = br.readLine();
	            }
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public static void printLog(Process p){
		  final InputStream is1 = p.getInputStream();   
          new Thread(new Runnable(){
              public void run() {
                  BufferedReader br = new BufferedReader(new InputStreamReader(is1));
                  try {
                     String outputLine = null;
                      while((outputLine=br.readLine())!= null) 
                    	  System.out.println("printLog--"+outputLine);
//                           commandOutput.add(outputLine);
                      }catch (IOException e) {
                          e.printStackTrace();
                          }
                      }
              }).start();
              InputStream is2 = p.getErrorStream();   
              BufferedReader br2 = new BufferedReader(new InputStreamReader(is2));
              StringBuilder buf = new StringBuilder();
              String line = null;
              try {
				while((line = br2.readLine()) != null) buf.append(line);
			} catch (IOException e) {
				e.printStackTrace();
			}
              System.out.println("result:" + buf);
//              while (br2.readLine() != null);
//              try {
//                  p.waitFor();
//                  }catch (InterruptedException e){
//                      e.printStackTrace();
//                      }
//                  queryExitValue=p.exitValue();
//                  System.out.println( p.exitValue());
                  
	}
}
